package com.tianzehua.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * file read and write
 * @author tianzehua
 * @date 2019/03/27
 */
public class NioTest5 {

    public static void main(String[] args) throws  Exception{
        FileInputStream inputStream = new FileInputStream("input.txt");
        FileOutputStream outputStream = new FileOutputStream("output.txt");
        FileChannel inputStreamChannel = inputStream.getChannel();
        FileChannel outputStreamChannel = outputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(512);

        while (true){
            byteBuffer.clear();

            /*  如果你没有对应的clear ，那么在第二次进行调用的时候，因为position和limit都指向了相同的位置，所以导致不管channel中有没有数据，都不会被执行
            * 所以产生的read 的值就是0 ，那么这样就会造成反复的读取buffer 中的值。*/

            /*  如果已经到达了流的结尾，则返回-1 */
            int read = inputStreamChannel.read(byteBuffer);

            if (read == -1){
                break;
            }
            byteBuffer.flip();
            outputStreamChannel.write(byteBuffer);
        }
        inputStream.close();
        outputStream.close();
    }
}
